#ifndef TOON_HAIR_FORWARD_PASS_INCLUDED
#define TOON_HAIR_FORWARD_PASS_INCLUDED

#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

struct Attributes
{
    float4 positionOS : POSITION;
    float3 normalOS : NORMAL;
    float2 texcoord : TEXCOORD0;
    UNITY_VERTEX_INPUT_INSTANCE_ID
};

struct Varyings
{
    float4 positionCS : SV_POSITION;
    float2 uv : TEXCOORD0;
    float3 positionWS : TEXCOORD1;
    float3 normalWS : TEXCOORD2;
    float3 viewDirWS : TEXCOORD3;
    float fogFactor : TEXCOORD4;
    float3 normalVS : TEXCOORD5;  // 视图空间法线，用于MatCap计算
    #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    float4 shadowCoord : TEXCOORD6;
    #endif
    UNITY_VERTEX_INPUT_INSTANCE_ID
    UNITY_VERTEX_OUTPUT_STEREO
};

CBUFFER_START(UnityPerMaterial)
// 这些属性会被 ForwardLit 和 Overlay Pass 共享
float4 _BaseMap_ST;
float4 _BaseColor;
float _MainAlphaScale; // 新增: 主 Pass Alpha 缩放
float _MatCapIntensity;
float4 _MatCapColor;
float _ShadowStrength;
float4 _ShadowColor;
float _AOMultiplier;
float _RampOffset;
float _RampSmooth;
// 散射效果参数
float4 _ScatterColor;
float _ScatterPower;
float _ScatterThreshold;
float _ScatterSmooth;
float _TranslucencyPower;

// 眉毛遮罩参数
float _UseEyebrowMask;
float _EyebrowMaskStrength;
float4 _EyebrowMaskOffset;
float4 _EyebrowMaskTiling;
float _DebugEyebrowMask;
float _EyebrowTransparency; // 眉毛区域的透明度值 (0=完全透明)
float _EyebrowEdgeSmooth; // 眉毛边缘平滑过渡

half3 _FinalColor; 
CBUFFER_END

TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap);
TEXTURE2D(_HMMap); SAMPLER(sampler_HMMap);
TEXTURE2D(_MatCapTex); SAMPLER(sampler_MatCapTex);
TEXTURE2D(_RampTex); SAMPLER(sampler_RampTex);
// 眉毛遮罩全局RT
TEXTURE2D(_EyebrowMaskTexture); SAMPLER(sampler_EyebrowMaskTexture);

Varyings vert(Attributes input)
{
    Varyings output = (Varyings)0;
    UNITY_SETUP_INSTANCE_ID(input);
    UNITY_TRANSFER_INSTANCE_ID(input, output);
    UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
    
    output.uv = TRANSFORM_TEX(input.texcoord, _BaseMap);
    
    VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
    VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS);
    
    output.positionCS = vertexInput.positionCS;
    output.positionWS = vertexInput.positionWS;
    output.normalWS = normalize(normalInput.normalWS);
    output.viewDirWS = GetWorldSpaceNormalizeViewDir(output.positionWS);
    output.fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
    
    // 计算视图空间法线，用于MatCap UV计算
    output.normalVS = TransformWorldToViewDir(output.normalWS);
    
    #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    output.shadowCoord = GetShadowCoord(vertexInput);
    #endif
    
    return output;
}

half4 frag(Varyings input) : SV_Target
{
    UNITY_SETUP_INSTANCE_ID(input);
    UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    
    // 基础色
    half4 diffuseColor = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, input.uv) * _BaseColor;
    
    // 提取HM图各通道信息
    half4 hmTexture = SAMPLE_TEXTURE2D(_HMMap, sampler_HMMap, input.uv);
    half specularMask = hmTexture.r;  // 高光遮罩
    half aoMask = hmTexture.b;        //AO
    half shadowMask = hmTexture.g;    // 阴影遮罩 (G通道)
    
    // 基本光照计算
    #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
    Light mainLight = GetMainLight(input.shadowCoord);
    #else
    Light mainLight = GetMainLight();
    #endif
    
    float3 normalWS = normalize(input.normalWS);
    float3 viewDirWS = normalize(input.viewDirWS);
    float NdotL = dot(normalWS, mainLight.direction); // 直接使用 NdotL [-1, 1]

    float normalOffset = shadowMask * _ShadowStrength;
    float rampInput = NdotL * 0.5 + 0.5 + normalOffset + _RampOffset; // 把减号改成加号

    // 采样Ramp贴图，使用 smoothstep 控制边界
    float rampUV_X = smoothstep(0.0, _RampSmooth, rampInput);
    half3 rampColor = SAMPLE_TEXTURE2D(_RampTex, sampler_RampTex, float2(rampUV_X, 0.5)).rgb;

    // 使用 Ramp 结果混合基础色和阴影色
    half3 shadedColor = lerp(_ShadowColor.rgb * diffuseColor.rgb, diffuseColor.rgb, rampColor.r); // 用 Ramp 的 R 通道混合

    // 应用AO遮罩 (G通道)
    half aoFactor = lerp(1.0, 1.0 - aoMask, _AOMultiplier); // AO 应该使颜色变暗
    
    // 计算MatCap高光
    float2 matcapUV = normalize(input.normalVS).xy * 0.5 + 0.5;
    half3 matcapColor = SAMPLE_TEXTURE2D(_MatCapTex, sampler_MatCapTex, matcapUV).rgb;
    half3 specularColor = matcapColor * specularMask * _MatCapIntensity * _MatCapColor.rgb;
    
    // 计算散射效果
    half3 scatterLight = 0;
    #if defined(_SCATTERING)
        // 计算光源方向与视线方向的半角向量
        float3 H = normalize(mainLight.direction + viewDirWS);
        
        // 计算透射效果 (光从背面穿过)
        float VdotL = dot(-viewDirWS, mainLight.direction);
        float backLight = pow(saturate(VdotL), _TranslucencyPower) * 0.5;
        
        // 计算正面的散射
        float NdotV = dot(normalWS, viewDirWS);
        float scatterFactor = pow(1.0 - saturate(NdotV), _ScatterPower);
        
        // 结合透光和散射
        float finalScatter = saturate(scatterFactor + backLight);
        finalScatter = smoothstep(_ScatterThreshold - _ScatterSmooth * 0.5, 
                                 _ScatterThreshold + _ScatterSmooth * 0.5, 
                                 finalScatter);
        
        // 在背光处增强效果
        float lightFacingFactor = saturate(1.0 - NdotL * 0.5 + 0.5);
        scatterLight = _ScatterColor.rgb * finalScatter * _ScatterColor.a * lightFacingFactor;
    #endif

    // 组合最终颜色
    _FinalColor = shadedColor * mainLight.color * aoFactor; // 应用 AO
    _FinalColor += specularColor; // 添加 MatCap 高光
    _FinalColor += scatterLight;  // 添加散射效果
    _FinalColor *= mainLight.shadowAttenuation; // 应用动态阴影
    
    // 应用环境光 (也受 AO 影响)
    float3 ambient = SampleSH(normalWS);
    _FinalColor += ambient * diffuseColor.rgb * 0.3 * aoFactor; // 环境光
    
    // 应用雾效
    _FinalColor = MixFog(_FinalColor, input.fogFactor);
    
    // 获取基础透明度
    float finalAlpha = diffuseColor.a;
    
    // 应用眉毛遮罩
    #if defined(_USE_EYEBROW_MASK)
        // 计算屏幕空间UV
        float2 screenUV = input.positionCS.xy / _ScreenParams.xy;
        
        // 应用缩放和偏移，用于精确对齐遮罩
        screenUV = screenUV * _EyebrowMaskTiling.xy + _EyebrowMaskOffset.xy;
        
        // 在某些平台可能需要处理Y轴翻转
        #if UNITY_UV_STARTS_AT_TOP
            // screenUV.y = 1.0 - screenUV.y;  // 如果需要，取消注释
        #endif
        
        // 采样眉毛遮罩
        float eyebrowMask = SAMPLE_TEXTURE2D(_EyebrowMaskTexture, sampler_EyebrowMaskTexture, screenUV).r;
        
        // 平滑处理遮罩边缘
        eyebrowMask = smoothstep(_EyebrowEdgeSmooth, 1.0 - _EyebrowEdgeSmooth, eyebrowMask);
        
        // 直接设置眉毛区域的透明度，而不是乘以现有alpha
        // eyebrowMask为1的地方是眉毛区域
        if (eyebrowMask > 0.01) // 只处理眉毛区域
        {
            // 在眉毛区域应用自定义透明度
            // _EyebrowTransparency是眉毛区域想要保留的透明度(0=完全透明)
            finalAlpha = lerp(finalAlpha, finalAlpha * _EyebrowTransparency, eyebrowMask * _EyebrowMaskStrength);
        }
        
        // 调试显示遮罩
        #if defined(_DEBUG_EYEBROW_MASK)
            return float4(eyebrowMask.xxx, 1.0);
        #endif
    #endif
    
    return half4(_FinalColor, finalAlpha);
}

#endif // TOON_HAIR_FORWARD_PASS_INCLUDED